<template>
  <div>
    <div class="app-container">
      <el-form ref="postForm" :model="postForm" :label-position="'right'" label-width="80px">
        <el-row type="flex" justify="space-between" :gutter="20">
          <el-col :span="6">
            <el-form-item label="用户名:">
              <el-input v-model="postForm.searchName" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" size="small" @click="query()">查询</el-button>
              <el-button type="warning" size="small" @click="addInfo()">新增</el-button>
              <el-button type="warning" size="small" @click="showImport()">导入</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <el-table
        :data="tableData"
        border
      >
        <el-table-column
          prop="name"
          header-align="center"
          align="center"
          label="姓名"
        />
        <el-table-column
          prop="mobile"
          header-align="center"
          align="center"
          label="手机号"
        />
        <el-table-column
          prop="seniorLevel"
          header-align="center"
          align="center"
          label="级别"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.seniorLevel === 0">高管</span>
            <span v-else-if="scope.row.seniorLevel === 1">中层</span>
            <span v-else></span>
          </template>
        </el-table-column>
        <el-table-column
          prop="state"
          header-align="center"
          align="center"
          label="状态"
        >
          <template slot-scope="scope">
            <el-tag v-if="scope.row.state === 0" size="small" type="danger">禁用</el-tag>
            <el-tag v-else size="small">正常</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="button"
              class="el-button el-button--primary el-button--mini"
              @click="editInfo(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button
              type="button"
              class="el-button el-button--danger el-button--mini"
              v-if="scope.row.state === 0"
              @click="delInfo(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row type="flex" class="row-bg" justify="center">
        <el-pagination
          background
          layout="total,  prev, pager, next, jumper"
          :total="total"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          @current-change="handleCurrentChange"
        />
      </el-row>
    </div>
    <el-dialog
      :title="title"
      :visible.sync="centerDialogVisible"
      center
    >
      <el-form ref="info" :rules="rules" :model="info" label-position="left" label-width="200px">
        <el-form-item label="姓名:" prop="name">
          <el-input v-model="info.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号:" prop="mobile">
          <el-input v-model="info.mobile" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="级别:" prop="seniorLevel">
          <el-radio-group v-model="info.seniorLevel" style="padding: 10px;">
            <el-radio :label="0">
              高管
            </el-radio>
            <el-radio :label="1">
              中层
            </el-radio>
            <el-radio :label="2">
              员工
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="状态:" prop="state">
          <el-radio-group v-model="info.state" style="padding: 10px;">
            <el-radio :label="1">
              有效
            </el-radio>
            <el-radio :label="0">
              禁用
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <el-form v-if="info.id">
        <el-row type="flex" justify="space-between" :gutter="20">
          <el-col :span="3">
          </el-col>
          <el-col :span="9">
            <el-form-item>
              <el-button @click="centerDialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addOrEdit()">确 定</el-button>
              <el-button type="primary" @click="addUserGroup()">新增用户组织</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div v-else slot="footer" class="dialog-footer">
        <el-button @click="centerDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEdit()">确 定</el-button>
      </div>
      <el-table
        v-if="info.id"
        :data="groupTableData"
        border
      >
        <el-table-column
          prop="businessGroupsName"
          header-align="center"
          align="center"
          label="商业集团"
        />
        <el-table-column
          prop="storeName"
          header-align="center"
          align="center"
          label="门店"
        />
        <el-table-column
          prop="roadStoreName"
          header-align="center"
          align="center"
          label="路店"
        />
        <el-table-column
          prop="position"
          header-align="center"
          align="center"
          label="职位"
        />
        <el-table-column
          fixed="right"
          header-align="center"
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="button"
              class="el-button el-button--primary el-button--mini"
              @click="editUserGroup(scope.$index, scope.row)"
            >编辑
            </el-button>
            <el-button
              type="button"
              class="el-button el-button--danger el-button--mini"
              @click="delUserGroup(scope.$index, scope.row)"
            >删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      :title="title"
      :visible.sync="importDialogVisible"
      center
      width="500px"
    >
      <el-upload
        class="upload-demo"
        drag
        :before-upload="beforeUpload"
        :on-success="uploadSuccess"
        :action="uploadUrl"
        :file-list="fileList"
        multiple
        style="margin-left: 50px;"
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip" slot="tip">只能上传xlsx类型，表格列名依次为：姓名、商业集团、区域、门店、路店、职位、手机号、级别（高管、中层，没有级别则不填）</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="用户组织编辑"
      :visible.sync="userGroupDialogVisible"
      center
      width="30%"
    >
      <el-form ref="info" :rules="rules" :model="info" label-position="left" label-width="200px">
        <el-form-item label="商业集团:">
          <el-select v-model="userGroup.businessGroups" @change="getStoreList" placeholder="请选择">
            <el-option
              v-for="group in businessGroupList"
              :key="group.id"
              :label="group.name"
              :value="group.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门店:" @change="getRoadStoreList" v-if="userGroup.businessGroups">
          <el-select v-model="userGroup.store" placeholder="请选择">
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="路店:" v-if="userGroup.store">
          <el-select v-model="userGroup.roadStore" placeholder="请选择">
            <el-option key="0" label="无" value=""></el-option>
            <el-option
              v-for="item in roadStoreList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="职位:">
          <el-input v-model="userGroup.position" placeholder="请输入职位" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="userGroupDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addOrEditUserGroup()">提 交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { addOrEdit, delInfo, getInfo, page, getUserGroupList, getUserGroup, delUserGroup, addOrEditUserGroup } from '@/api/app/appUser.js'
  import { getGroupList } from '@/api/system/sysGroup.js'
  import { getToken } from '@/utils/auth'

  export default {
    data() {
      return {
        // 总条数
        total: 0,
        // 每页显示个数
        pageSize: 10,
        // 页码
        currentPage: 1,
        postForm: { searchName: '' },
        info: {},
        tableData: [],
        editIndex: 0,
        centerDialogVisible: false,
        importDialogVisible: false,
        title: '新增',
        businessGroupList: [],
        storeList: [],
        roadStoreList: [],
        uploadUrl: process.env.BASE_API + '/system/appUser/importUser?Token=' + getToken(),
        fileList: [],
        groupTableData: [],
        userGroupDialogVisible: false,
        userGroup: {},
        userGroupEditIndex: 0,
        rules: {
          name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
          position: [{ required: true, message: '请输入职位', trigger: 'blur' }],
          mobile: [{ required: true, message: '请输入手机号', trigger: 'blur' }]
        }
      }
    },
    created() {
      this.getData()
      this.getBusinessGroup()
    },
    methods: {
      // 分页查询
      handleCurrentChange(val) {
        this.currentPage = val
        this.getData()
      },
      // 查询条件
      query() {
        this.currentPage = 1
        this.getData()
      },
      getData() {
        // 请求分页参数
        page(this.pageSize, this.currentPage, this.postForm.searchName).then(response => {
          this.total = response.count
          this.tableData = response.data
        })
      },
      // 新增
      addInfo() {
        this.title = '新增'
        this.info = {}
        this.centerDialogVisible = true
      },
      // 导入
      showImport() {
        this.title = '导入'
        this.importDialogVisible = true
        this.fileList = []
      },
      beforeUpload(file) {
        const type = file.name.split('.')[1]
        const isXlsx = type === 'xlsx'

        if (!isXlsx) {
          this.$message.error('上传文件只能是 xlsx 格式!')
        }
        return isXlsx
      },
      uploadSuccess(file) {
        if (file.data.haveError === false) {
          this.$notify({
            title: '成功',
            message: file.data.name + '上传成功',
            type: 'success',
            duration: 10000
          })
        } else {
          var message = ''
          if (file.data.haveError === true) {
            for (var i = 0; i < file.data.error.length; i++) {
              var str_1 = '第' + (file.data.error[i].rowIndex + 1) + '行' + file.data.error[i].errorFields + '；'
              message += str_1
            }
          }
          if (file.data.hasExist === true) {
            for (var num = 0; i < file.data.existList.length; num++) {
              var str_2 = '手机号为' + file.data.existList[num].mobile + '已存在；'
              message += str_2
            }
          }
          this.$notify.error({
            title: '存在失败数据',
            message: message,
            duration: 0
          })
        }
      },
      /**
       * 编辑
       * @param row
       */
      editInfo(index, row) {
        this.editIndex = index
        this.title = '编辑'
        this.centerDialogVisible = true
        getInfo(row.id).then(response => {
          this.info = response.data
          getUserGroupList(this.info.id).then(response => {
            this.groupTableData = response.data
          })
        })
      },
      addOrEdit: function() {
        this.$refs['info'].validate((valid) => {
          if (valid) {
            addOrEdit(this.info.id, this.info.name, this.info.mobile, this.info.seniorLevel, this.info.state).then(response => {
              this.centerDialogVisible = false
              if (this.info.id == null) {
                // 新增
                  this.tableData.unshift(response.data)
                this.$notify({
                  title: '成功',
                  message: '创建成功',
                  type: 'success',
                  duration: 2000
                })
              } else {
                // 编辑
                this.tableData.splice(this.editIndex, 1, response.data)
                this.$notify({
                  title: '成功',
                  message: '更新成功',
                  type: 'success',
                  duration: 2000
                })
              }
            })
          }
        })
      },
      delInfo(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delInfo(row.id).then(response => {
            this.tableData.splice(index, 1)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      },
      getBusinessGroup() {
        getGroupList(0).then(response => {
          this.businessGroupList = response.data
        })
      },
      getStoreList() {
        getGroupList(1, this.userGroup.businessGroups).then(response => {
          this.storeList = response.data
        })
      },
      getRoadStoreList() {
        getGroupList(2, this.userGroup.store).then(response => {
          this.roadStoreList = response.data
        })
      },
      // 新增用户组织
      addUserGroup() {
        this.userGroup = {}
        this.userGroupDialogVisible = true
      },
      // 编辑用户组织
      editUserGroup(index, row) {
        this.userGroupEditIndex = index
        this.userGroupDialogVisible = true
        getUserGroup(row.id).then(response => {
          this.userGroup = response.data
          this.getStoreList()
          this.getRoadStoreList()
        })
      },
      addOrEditUserGroup() {
        addOrEditUserGroup(this.userGroup.id, this.info.id, this.userGroup.businessGroups, this.userGroup.store, this.userGroup.roadStore, this.userGroup.position).then(response => {
          this.userGroupDialogVisible = false
          if (this.userGroup.id == null) {
            // 新增
            this.groupTableData.unshift(response.data)
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          } else {
            // 编辑
            this.groupTableData.splice(this.editIndex, 1, response.data)
            this.$notify({
              title: '成功',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }
        })
      },
      // 删除用户组织
      delUserGroup(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delUserGroup(row.id).then(response => {
            this.groupTableData.splice(index, 1)
            this.$notify({
              title: '成功',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
        })
      }
    }
  }
</script>

